package io.github.harmonly.controller;

import io.github.harmonly.entity.User;
import io.github.harmonly.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
public class AuthController {

    @Resource
    UserService service;

    @PostMapping("/doLogin")
    public String doLogin(HttpSession session, String account, String password) {
        if (service.auth(session, account, password)) return "redirect:index";
        session.setAttribute("login_error", true);
        return "redirect:login";
    }

    @PostMapping("/doRegister")
    public String doRegister(String name, String account, String password) {
        if (service.addUser(User.builder()
                .name(name)
                .account(account)
                .password(password)
                .role("student")
                .face("")
                .build())) return "redirect:login";
        return "redirect:register";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:login";
    }
}
